package com.sywl.glzh.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.sywl.glzh.domain.Product;
import com.sywl.glzh.domain.ProductType;

/**
 * 后台产品浏览跟添加
 * @author itachi
 *
 */
@Controller
public class ProductManagerController {
	
	/**
	 * 按产品类型显示列表
	 * @param type
	 * @param page
	 * @param size
	 * @param uiModel
	 * @return
	 */
	@RequestMapping("product")
	public String list(long type, @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
		ProductType pt = ProductType.findProductType(type);
		if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("products", Product.findProductsByType(pt).setFirstResult(firstResult).setMaxResults(sizeNo).getResultList());
            float nrOfPages = (float) Product.countProducts() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1 : nrOfPages));
        } else {
            uiModel.addAttribute("products", Product.findProductsByType(pt).getResultList());
        }
		uiModel.addAttribute("type", pt);
        return "product/list";
	}
	
	/**
	 * 添加产品表单
	 * 传递产品类型ID
	 * @param type
	 * @param create
	 * @param model
	 * @return
	 */
	@RequestMapping("productss")
	public String create(long type, String create, Model model) {
		//model.addAttribute("type", type);
		model.addAttribute("product", new Product());
        model.addAttribute("producttypes", ProductType.findAllProductTypes());
		return "productss/create";
	}
	
}
